package com.glory.gloryquickui.utils

import android.app.Application
import android.content.Context
import okhttp3.OkHttpClient
import rxhttp.wrapper.cookie.CookieStore
import rxhttp.wrapper.param.Param
import rxhttp.wrapper.param.RxHttp
import rxhttp.wrapper.ssl.HttpsUtils
import java.io.File
import java.util.concurrent.TimeUnit
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLSession

/**
 * @author HX
 * @date 2021/5/21
 * @desc
 */
open class InitUtils {
    companion object {
        var app: Context? = null
        var instance: Application? = null
        var BaseUrl = "http://220.248.78.106:3303"
        var FileUrl = "http://220.248.78.106:3303/Version.txt"

        //屏幕宽高
        var SCREEN_WIDTH = 0
        var SCREEN_HEIGHT = 0
        var Token = ""

        fun init(application: Application) {
            app = application
            instance = application
            val metrics = app!!.resources.displayMetrics
            SCREEN_WIDTH = metrics.widthPixels
            SCREEN_HEIGHT = metrics.heightPixels
            initRxhttp()
        }

        fun initRxhttp() {
            val file = File(app!!.externalCacheDir, "RxHttpCookie")
            val sslParams = HttpsUtils.getSslSocketFactory()
            val client: OkHttpClient = OkHttpClient.Builder()
                .cookieJar(CookieStore(file))
                .connectTimeout(30, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager) //添加信任证书
                .hostnameVerifier(HostnameVerifier { hostname: String?, session: SSLSession? -> true }) //忽略host验证
                //            .followRedirects(false)  //禁制OkHttp的重定向操作，我们自己处理重定向
                //            .addInterceptor(new RedirectInterceptor())
                //            .addInterceptor(new TokenInterceptor())
                .build()
            //RxHttp初始化，自定义OkHttpClient对象，非必须
            RxHttp.init(client)
            RxHttp.setDebug(true)
            RxHttp.setOnParamAssembly { p: Param<*>? ->
                p!!.addHeader("Authorization", "Bearer $Token") //添加公共请求头
            }
        }
    }
}